﻿var $ = layui.$;

var laydate = layui.laydate;
// 渲染
laydate.render({
    elem: '#dateConversion'
});

layui.use(['form', 'jquery'], function () {
    var form = layui.form;
    var $ = layui.jquery;

    $('#addRowBtn').on('click', function () {
        // 获取数据表格和行数
        const table = document.getElementById('dataTable');
        const numRows = table.rows.length;

        // 如果行数超过1，则禁止添加新行
        if (numRows > 1) {
            layer.msg('已达到最大行数限制，不能再添加新行！');
            return;
        }

        var rowCount = $('#dataTable tbody tr').length + 1; // 获取当前行数并加1作为新行的序号

        var newRowHtml = '<tr>' +
            '<td>' + rowCount + '</td>' + // 新增自增序号列
            `<td>
            <div class="select-wrapper">
					<select name="growSheepEars" id="growSheepEars" lay-filter="growSheepEars" lay-verify="required">
						<option value="">育成羊耳号</option>
					</select>
			</div>
            </td>` +
            `<td>
            <div class="select-wrapper">
					<select name="transferBuilding" id="transferBuilding" lay-filter="transferBuilding" lay-verify="required" lay-search="">
						<option value="">转入栋舍</option>
					</select>
			</div>
            </td>`+
            `<td>
            <div class="select-wrapper">
					<select name="driveField" id="driveField" lay-filter="driveField" lay-verify="required" lay-search="">
						<option value="">转入栏位</option>
					</select>
			</div>
            </td>`+
            `<td>
                        <input type="text" name="currentBuilding" id="currentBuilding" lay-verify="required" autocomplete="off" class="layui-input" style="width:120px" readonly>
            </td>`+
            `<td>
                        <input type="text" name="currentField" id="currentField" lay-verify="required" autocomplete="off" class="layui-input" style="width:120px" readonly>
            </td>`+
            `<td>
            <div class="select-wrapper">
					<select name="sex" id="sex" disabled>
                        <option value=""></option>
						<option value="true">公</option>
						<option value="false">母</option>
					</select>
			</div>
            </td>`+
            `<td>
                        <input type="text" name="ageTransplanting" id="ageTransplanting" lay-verify="required" autocomplete="off" class="layui-input" style="width:120px">
            </td>`+ '</tr>';
        $('#dataTable tbody').append(newRowHtml);
        form.render(); // 重新渲染表单，使新增的输入框生效

        //绑定后裔耳号
        $(document).ready(function () {
            $.ajax({
                url: 'http://10.31.60.18:8000/ArchivesGetRout/api/Archives/ArchivesAllInfo',
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    var enumData = res; // 直接使用返回的数据
                    var select = $('#growSheepEars');
                    $.each(enumData, function (index, item) {
                        if (item.sheepType == "后裔") {
                            // 使用正确的字段添加选项到下拉框中
                            var option = $('<option>').val(item.earNnumber).text(item.earNnumber);
                            select.append(option);
                        }
                    });
                    // 手动触发 layui 组件的渲染
                    layui.form.render('select');
                },
                error: function () {
                    // 处理 AJAX 请求失败的情况
                    console.error('Failed to fetch data for dropdown.');
                }
            });
        });

        // 添加change事件监听器
        $('#growSheepEars').change(function () {
            var selectedValue = $(this).val();
            $.ajax({
                url: 'http://10.31.60.18:8000/ArchivesGetRout/api/Archives/ArchivesGetByEarNumberInfo?EarNumber=' + selectedValue,
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    if (res == undefined) {
                        $("#sex").val("")
                        $("#currentBuilding").val("")
                        $("#currentField").val("")
                    } else {
                        $("#sex").val(res.sheepGender.toString())
                        $("#currentBuilding").val(res.cottageId)
                        $("#currentField").val(res.field)
                    }
                },
                error: function () {
                    // 处理 AJAX 请求失败的情况
                    console.error('Failed to fetch data for dropdown.');
                }
            });
        });

        //绑定栋舍
        var data = [];
        $(document).ready(function () {
            $.ajax({
                url: 'http://10.31.60.18:8000/AuthorizationGetRout/api/Cottage/CootList',
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    data = res; // 直接使用返回的数据
                    var select = $('#transferBuilding');
                    $.each(data, function (index, item) {
                        // 使用正确的字段添加选项到下拉框中
                        var option = $('<option>').val(item.name).text(item.name);
                        select.append(option);
                    });
                    // 手动触发 layui 组件的渲染
                    layui.form.render('select');
                },
                error: function () {
                    // 处理 AJAX 请求失败的情况
                    console.error('Failed to fetch data for dropdown.');
                }
            });
        });

        // 栋舍栏位二级联动
        $('#transferBuilding').change(function () {
            var name = $("#transferBuilding").val();
            var id = 0;
            $.each(data, function (index, item) {
                if (name == item.name) {
                    id = item.id;
                }
            });
            //监听到了下拉框选择的选项，传递过来
            $.get({
                url: 'http://10.31.60.18:8000/AuthorizationGetRout/api/Cottage/FieidList', // 后端枚举数据接口地址
                data: {
                    id: id
                },
                dataType: "json",
                success: function (res) {
                    $("#driveField").empty();
                    var option = '<option value=" ">' + "请选择栏位" + '</option>';
                    $("#driveField").append(option);
                    $.each(res, function (index, item) {
                        // 使用正确的字段添加选项到下拉框中
                        var option = $('<option>').val(item.name).text(item.name);
                        $('#driveField').append(option);
                    });
                    // 手动触发 layui 组件的渲染
                    layui.form.render('select');
                },
                error: function () {
                    // 处理 AJAX 请求失败的情况
                    console.error('Failed to fetch data for dropdown.');
                }
            });
        });

        updateTableScroll(); // Update table scrolling after adding new row
    });

    function updateTableScroll() {
        // Adjust table scroll after adding new rows
        var tableContainer = $('#dataTable').parent();
        tableContainer.css('overflow-x', 'auto'); // Enable horizontal scrolling
        tableContainer.css('max-width', '100%'); // Ensure table does not exceed parent width
    }
});

// 删除行的函数
function deleteRow(btn) {
    $(btn).closest('tr').remove();
}

function saveRow() {
    var inputValues = {
        dateConversion: $("#dateConversion").val(),
        growSheepEars: $("#growSheepEars").val(),
        transferBuilding: $("#transferBuilding").val(),
        driveField: $("#driveField").val(),
        currentBuilding: $("#currentBuilding").val(),
        currentField: $("#currentField").val(),
        sex: $("#sex").val() == "true" ? true : false,
        ageTransplanting: $("#ageTransplanting").val() == "" ? null : $("#ageTransplanting").val(),
    }

    console.log(inputValues)

    // 获取单个字段的输入框元素
    const dateConversion = document.getElementById('dateConversion');

    if (dateConversion.value.trim() === '') {
        layer.msg('转种日期不能为空！');
        return;
    }

    // 获取单个字段的输入框元素
    const growSheepEars = document.getElementById('growSheepEars');

    if (growSheepEars.value.trim() === '') {
        layer.msg('育成羊耳号不能为空！');
        return;
    }

    // 在这里您可以执行其他操作，例如发送到服务器端进行处理
    $.ajax({
        type: 'POST',
        url: 'http://10.31.60.18:8000/ProduceSetRout/api/ProgenyTransfer/AddProgenyTransfer', // 根据实际情况修改ControllerName和ActionName
        //url: 'http://localhost:5051/api/WeaningOfLamb/AddWeaningOfLamb', // 根据实际情况修改ControllerName和ActionName
        data: JSON.stringify(inputValues),
        contentType: "application/json",
        success: function (response) {
            if (response.code == 200) {
                UpdArchives(inputValues)
                layer.msg('添加成功', { icon: 1 }, function () {
                    location.href = '/ProgenyTransfer/ProgenyTransferShow'
                });
            } else {
                layer.msg('添加失败');
            }
        },
        error: function (xhr, status, error) {
            // 处理错误响应
            console.error(error);
        }
    });
}

function UpdArchives(inputValues) {
    $.ajax({
        url: 'http://10.31.60.18:8000/ArchivesGetRout/api/Archives/ArchivesGetByEarNumberInfo?EarNumber=' + inputValues.growSheepEars,
        type: 'get',
        dataType: 'json',
        success: function (data) {
            var values = {};
            if (data.sheepGender) {
                values = {
                    id: data.id,
                    earNnumber: data.earNnumber,
                    electronicEarNumber: data.electronicEarNumber,
                    sheepBreed: data.sheepBreed,
                    sheepGender: data.sheepGender,
                    sheepBir: data.sheepBir,
                    presence: data.presence,
                    growthStage: data.growthStage,
                    sheepType: "种公",
                    cottageId: inputValues.transferBuilding,
                    field: inputValues.driveField,
                    reproductiveState: data.reproductiveState,
                    pregnancyTest: data.pregnancyTest,
                    statusDays: data.statusDays,
                    productionGrade: data.productionGrade,
                    salesGrade: data.salesGrade,
                    geneticGrade: data.geneticGrade,
                    birthWeight: data.birthWeight,
                    weaningDate: data.weaningDate,
                    fatherEarNumber: data.fatherEarNumber,
                    motherEarNumber: data.motherEarNumber,
                    dayAge: data.dayAge,
                    monthAge: data.monthAge,
                    weaningAge: data.weaningAge,
                    sheepBir: data.sheepBir,
                    archivesRemark: data.archivesRemark,
                    archivesPicture: data.archivesPicture,
                    placeBirth: data.placeBirth,
                    inDate: data.inDate
                }
            } else {
                values = {
                    id: data.id,
                    earNnumber: data.earNnumber,
                    electronicEarNumber: data.electronicEarNumber,
                    sheepBreed: data.sheepBreed,
                    sheepGender: data.sheepGender,
                    sheepBir: data.sheepBir,
                    presence: data.presence,
                    growthStage: data.growthStage,
                    sheepType: "种母",
                    cottageId: inputValues.transferBuilding,
                    field: inputValues.driveField,
                    reproductiveState: data.reproductiveState,
                    pregnancyTest: data.pregnancyTest,
                    statusDays: data.statusDays,
                    productionGrade: data.productionGrade,
                    salesGrade: data.salesGrade,
                    geneticGrade: data.geneticGrade,
                    birthWeight: data.birthWeight,
                    weaningDate: data.weaningDate,
                    fatherEarNumber: data.fatherEarNumber,
                    motherEarNumber: data.motherEarNumber,
                    dayAge: data.dayAge,
                    monthAge: data.monthAge,
                    weaningAge: data.weaningAge,
                    sheepBir: data.sheepBir,
                    archivesRemark: data.archivesRemark,
                    archivesPicture: data.archivesPicture,
                    placeBirth: data.placeBirth,
                    inDate: data.inDate
                }
            }
            console.log(values)
            // 在这里您可以执行其他操作，例如发送到服务器端进行处理
            $.ajax({
                type: 'PUT',
                url: 'http://10.31.60.18:8000/ArchivesSetRout//api/Archives/ArchivesUpdate', // 根据实际情况修改ControllerName和ActionName
                data: JSON.stringify(values),
                contentType: "application/json",
                success: function (response) {
                    console.log(response)
                },
                error: function (xhr, status, error) {
                    // 处理错误响应
                    console.error(error);
                }
            });
        },
        error: function () {
            // 处理 AJAX 请求失败的情况
            console.error('Failed to fetch data for dropdown.');
        }
    });
}